﻿using DataSync.Core;
using Furion.Logging.Extensions;
using Microsoft.Data.SqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SqlDataAdapter = Microsoft.Data.SqlClient.SqlDataAdapter;

namespace DataSync.Application
{
    /// <summary>
    /// AppSys表数据同步
    /// </summary>
    public class AppSysDataSync
    {
        public static string SyncData(string tableName, SqlSugarScope source, SqlSugarScope target)
        {
            try
            {
                //查询数据
                var selectTableSql = $"SELECT * FROM {tableName}";
                //创建datatable（源数据）
                var sourceDataTable = source.Ado.GetDataTable(selectTableSql);

                if (sourceDataTable != null && sourceDataTable.Rows.Count > 0)
                {
                    //新增列 MD5
                    DataBaseInfoService.DataTableAddColumsMd5(sourceDataTable);
                }
                //创建datatable（目标表数据）
                var targetDataTable = target.Ado.GetDataTable(selectTableSql);

                if (targetDataTable != null && targetDataTable.Rows.Count > 0)
                {
                    //新增列 MD5
                    DataBaseInfoService.DataTableAddColumsMd5(targetDataTable);
                }
                // 计算是否存在差异
                var tempTable = new DataTable();
                var tempExceptTable = (from sourceRow in sourceDataTable.AsEnumerable()
                                       where
                                       !(from targetRow in targetDataTable.AsEnumerable() select targetRow.Field<string>("MD5")).Contains(
                                       sourceRow.Field<string>("MD5"))
                                       select sourceRow);
                if (tempExceptTable != null && tempExceptTable.Count() > 0)
                {
                    tempTable = tempExceptTable.CopyToDataTable();
                }
                if (tempTable != null && tempTable.Rows.Count > 0)
                {
                    //存在差异
                    //删除标识列和MD5列
                    DataBaseInfoService.DatatableRemoveCloumns(targetDataTable);
                    //删除目标表数据，导入源数据表数据
                    foreach (DataRow dataRow in targetDataTable.Rows)
                    {
                        var deleteDataSql = DataTableHelper.ConstructDeleteSql(tableName, dataRow);
                        //commandTarget.CommandText = deleteDataSql;
                        //commandTarget.ExecuteNonQuery();
                        target.Ado.ExecuteCommand(deleteDataSql);
                    }
                    //删除标识列和MD5列
                    DataBaseInfoService.DatatableRemoveCloumns(sourceDataTable);
                    foreach (DataRow dataRow in sourceDataTable.Rows)
                    {
                        var AddDataSql = DataTableHelper.ConstructInsertSql(tableName, dataRow);
                        //commandTarget.CommandText = deleteDataSql;
                        //commandTarget.ExecuteNonQuery();
                        target.Ado.ExecuteCommand(AddDataSql);
                    }
                }
                // }

                //}
                return $"{tableName}表同步完成！";
            }
            catch (Exception ex)
            {
                ("Error occurred while connecting to database or fetching data from tables.\n" + ex.Message).LogError();
                return $"{tableName}表同步失败！";
            }

        }

    }
}
